package client.comm.commlib.widget

import android.content.Context
import android.graphics.Canvas
import android.graphics.Rect
import android.util.AttributeSet
import android.util.TypedValue
import androidx.appcompat.widget.AppCompatTextView

class OldPriceTextView : AppCompatTextView {
    private var rect: Rect? = Rect()

    constructor(context: Context?) : super(context!!) {
        init()
    }

    constructor(context: Context?, attrs: AttributeSet?) : super(
        context!!, attrs
    ) {
        init()
    }

    constructor(context: Context?, attrs: AttributeSet?, defStyleAttr: Int) : super(
        context!!, attrs, defStyleAttr
    ) {
        init()
    }

    private fun init() {
        rect = Rect()
    }

    override fun onSizeChanged(w: Int, h: Int, oldw: Int, oldh: Int) {
        super.onSizeChanged(w, h, oldw, oldh)
        val width = paint.measureText(text.toString())
        rect!![paddingLeft, h / 2, (paddingLeft + width).toInt()] =
            (h / 2 + TypedValue.applyDimension(
                TypedValue.COMPLEX_UNIT_DIP,
                1f,
                resources.displayMetrics
            )).toInt()
    }

    override fun onDraw(canvas: Canvas) {
        super.onDraw(canvas)
        canvas.drawRect(rect!!, paint)
    }

    override fun setText(text: CharSequence, type: BufferType) {
        super.setText(text, type)
        if (rect != null) {
            val width = paint.measureText(getText().toString())
            val h = height
            rect!![paddingLeft, h / 2, (paddingLeft + width).toInt()] =
                (h / 2 + TypedValue.applyDimension(
                    TypedValue.COMPLEX_UNIT_DIP,
                    1f,
                    resources.displayMetrics
                )).toInt()
            invalidate()
        }
    }
}